package com.fschina.devtools.Base64Util;

import com.freesoft.commons.utils.response.ResponseEntity;
import com.fschina.devtools.enums.ResponseCodeEnum;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: dev-tools
 * @description: Base64编码工具类
 * @author: QinYanqing
 * @create: 2018-08-27 10:10
 **/

@Controller
@RequestMapping("base64")
public class Base64UtilController {

     @RequestMapping("bas64page")
    public String  showPage(){
        return "base64/base64";
    }

    @RequestMapping("encode")
    @ResponseBody
    public ResponseEntity<String> encode(String source){
        ResponseEntity<String> result=new ResponseEntity<>();
        try {
             String base64Str= Base64.encodeBase64String(source.getBytes());
             result.setCode(ResponseCodeEnum.SUCCESS.getCode());
             result.setMessage(ResponseCodeEnum.SUCCESS.getValue());
             result.setData(base64Str);
             return result;
        }catch (Exception e){
            result.setCode(ResponseCodeEnum.FAILED.getCode());
            result.setMessage(ResponseCodeEnum.FAILED.getValue());
            return result;
        }
    }

    @RequestMapping("decode")
    @ResponseBody
    public ResponseEntity<String> decode(String base64str){
        ResponseEntity<String> result=new ResponseEntity<>();
        try {
            byte[] resultStr= Base64.decodeBase64(base64str);
            result.setCode(ResponseCodeEnum.SUCCESS.getCode());
            result.setMessage(ResponseCodeEnum.SUCCESS.getValue());
            result.setData(new String(resultStr));
            return result;
        }catch (Exception e){
            result.setCode(ResponseCodeEnum.FAILED.getCode());
            result.setMessage(ResponseCodeEnum.FAILED.getValue());
            return result;
        }
    }
}
